//配置信息
/**
 * @openapi
 * tags:
 * - name: wechat
 *   description: 微信相关服务
 */
const router = require("express-promise-router")(); //允许路由返回promise,方便使用async/await
const WechatService=require("../services/wechat");
const UserService=require("../services/user");
const KindService=require("../services/kind");
const WhiteListService=require("../services/white_list")
const config = require("../config/config");
const BorrowTimeService=require("../services/borrow_time");
const LogService = require("../services/log");
const CheckRecordService = require("../services/check_record");
const CabinetService = require("../services/cabinet");
const moment=require("moment")

/**
 * @openapi
 * /wechat/get_user:
 *   get:
 *     tags:
 *     - wechat
 *     summary: 根据code取得用微信用户信息,如果用户已经在系统中,更新其access_token信息
 *     parameters:
 *       - in: query
 *         name: code
 *         required: true
 *         schema:
 *           type: string
 *         description: 扫码回调得到的code
 */
router.get('/get_user', async (req, res) => {
    const code=req.query.code;
    if(!code){
        throw new Error("no code");
    }
    const result=await WechatService.get_access_token_by_code(code);
    if(result.errcode){
        res.status(400).json(result);
    }else{
        if(result.unionid){
            //如果用户已经绑定微信,需要将unionid和access_token更新到数据库中
            const username=await UserService.get_username_by_unionid(result.unionid);
            if(username){
                await UserService.update_access_token(username,result.access_token);
            }
        }
        res.json(result);
    }
});

/**
 * @openapi
 * /wechat/get_user_xcx:
 *   get:
 *     tags:
 *     - wechat
 *     summary: 根据code取得用微信用户信息,如果用户已经在系统中,更新其access_token信息
 *     parameters:
 *       - in: query
 *         name: code
 *         required: true
 *         schema:
 *           type: string
 *         description: 小程序授权回调得到的code
 */
router.get('/get_xcx_user', async (req, res) => {
    const code=req.query.code;
    if(!code){
        throw new Error("no code");
    }
    const result=await WechatService.get_xcx_access_token_by_code(code);
    if(result.errcode){
        res.status(400).json(result);
    }else{
        let user;
        if(result.unionid){
            //如果用户已经绑定微信,需要将unionid和access_token更新到数据库中
            user=await UserService.get_user_by_unionid(result.unionid);
            // if(username){
            //     await UserService.update_access_token(username,result.access_token);
            // }
        }
        res.json({result,user});
    }
});

/**
 * @openapi
 * /wechat/get_user_by_unionid:
 *   get:
 *     tags:
 *     - user
 *     summary: 根据unionid取得用户并更新session_key
 *     parameters:
 *       - in: path
 *         name: unionid
 *         required: true
 *         schema:
 *           type: string
 *         description: 微信用户的unionid
 *     responses:
 *       200:
 *         description: 修改成功
 *       400:
 *         description: 失败
 */
router.get('/get_user_by_unionid', async (req, res) => {
    const unionid=req.query.unionid;
    const session_key=req.query.session_key;
    if(!unionid){
        throw new Error("no unionid");
    }
    const user=await UserService.get_user_by_unionid(unionid);
    if(user){
        await UserService.update_session_key(user.username,session_key);
        res.json(user);
    }else{
        res.status(400).json({"error":"not found user"});
    }
});

/**
 * @openapi
 * /wechat/bind_unionid_to_user:
 *   post:
 *     tags:
 *     - wechat
 *     summary: 绑定用户unionid
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               username:
 *                 type: string
 *               unionid:
 *                 type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 成功，返回user
 *       400:
 *         description: 失败 {error:"绑定失败"}
 */

router.post('/bind_unionid_to_user', async (req, res) => {
    const {username,unionid,session_key}=req.body;
    try{
        const user=await UserService.update_unionid_and_access_token(username,unionid,session_key);
        await UserService.link_user_and_wechat(username,unionid,session_key);//首次绑定的时候必须调用，相当于注册wechat_auth
        req.session.user=user;
        delete user.password;//返回前去除密码
        delete user.password_aes;//返回前去除密码
        delete user.password_md5;//返回前去除密码
        LogService.addLog(user,"用户",`小程序绑定用户`);
        res.status(200).json(user);//成功 200
        // return;
    }catch (e) {
        // res.status(400).json({error:e.toString()}); //失败 400,返回{error:"..."}
        res.send({status: "fail", err:e.toString()});
        // return;
    }
});

router.get('/kinds', async (req, res) => {
    const category=req.query.category;
    console.log("category",category);
    if(!category){
        throw new Error("no category");
    }
    const kinds=await KindService.getWechatKindsByCategory(category);
    res.send(kinds);
});


router.get('/boxes', async (req, res) => {
    const username=req.query.username;
    if(!username){
        throw new Error("no username");
    }
    const kinds=await WhiteListService.getUserKinds(username);
    res.send(kinds);
});


router.get('/categorys', async (req, res) => {
    let categorys=await KindService.getCategorys();
    categorys=categorys.map(c => c.category);
    if(!categorys){
        categorys=config.categorys;
    }
    res.send(categorys);
});

router.post('/add_to_list', async (req, res) => {
    const {username,kind,count,isApply}=req.body;
    if(!username){
        throw new Error("no username");
    };
    // const schedule=await BorrowTimeService.getSchedule(scheduleId);
    // const users=schedule.users&&schedule.users.length||0;
    // if(schedule.capacity <= users){
    //     res.send({status: "fail", err:"该时间段预约人数已满！"});
    //     return
    // }
    const _borrow_list=await KindService.getUserBorrowList(username);
    const borrow_list = _borrow_list.map(l => { return { kind: l.list[0].kind, ...l } });
    const existKind = borrow_list.find(l => l.kind && l.kind.objectId === kind.objectId||l.kind && l.kind._id === kind.objectId&&l.hasReturn!==true)
    console.log("existKind",existKind)
    if(existKind&&existKind==="个人实验箱"){
        res.send({status: "fail", err:"已经申领过该物品！"});
    }else {
        const kindId=kind.objectId||kind._id
        let whiteList=null;
        if(kind.hasCode){
            whiteList=await WhiteListService.getUserWhiteList(username,kindId);
        }
        const list=await KindService.addToList(username,kind,count,null,isApply,null,whiteList?whiteList.objectId:null);
        res.send(list);
    }

});
router.post('/borrow_list', async (req, res) => {
    const {username}=req.body;
    if(!username){
        throw new Error("no username");
    }
    const list=await KindService.getUserBorrowList(username);
    res.send(list);
});

router.post('/borrow_list_id', async (req, res) => {
    const {listId}=req.body;
    if(!listId){
        throw new Error("no listId");
    }
    const list=await KindService.getBorrowListById(listId);
    const fault_records=await KindService.getFaultRecords(listId);
    res.send({list,fault_records});
});

router.get('/all_borrow_list', async (req, res) => {
    const list=await KindService.getBorrowList();
    res.send(list);
});

router.get('/apply_times', async (req, res) => {
    const apply_times=await BorrowTimeService.getSchedules();
    res.send(apply_times);
});

router.post('/update_borrow_list', async (req, res) => {
    const {id,key,value}=req.body;
    if(!id){
        throw new Error("no id");
    }
    const list=await KindService.change_status(id,value,key);
    res.send(list);
});

router.post('/save_fault_record', async (req, res) => {
    const {listId,scheduleId,username,text}=req.body;
    if(!listId){
        throw new Error("no listId");
    }
    // const schedule=await BorrowTimeService.getSchedule(scheduleId);
    // const users=schedule.users&&schedule.users.length||0;
    // if(schedule.capacity <= users){
    //     res.send({status: "fail", err:"该时间段预约人数已满！"});
    //     return
    // }
//    await BorrowTimeService.addUser(scheduleId,username);
    const record=await KindService.addFaultRecord(listId,scheduleId,username,text)
    res.send(record);
});

//获取报修记录
router.get('/fault_records', async (req, res) => {
    const records=await KindService.getAllFaultRecords();
    res.send(records);
}
);

router.post('/update_fault_record', async (req, res) => {
    const {key,value,id}=req.body;
    const result=await KindService.update_fault_record(key,value,id)
    res.send(result);
});



router.get('/getSupplies', async (req, res) => {
    const supplies=await KindService.getSupplies();
    res.send(supplies);
});

router.post('/getAuditors', async (req, res) => {
    const teachers=await UserService.getTeachers();
    res.send(teachers);
});

router.post('/checkSuppliesNumber', async (req, res) => {
    const {kindId}=req.body;
    const result=await KindService.checkSuppliesNumber(kindId);
    res.send({ total: result }); // 将结果封装成对象返回
});


router.post('/checkIn', async function(req, res) {
    const {recordId,experimentId,stepName}=req.body;
    const result=await CheckRecordService.checkIn(recordId,experimentId,stepName);
    res.json(result);
});

router.post('/cancelCheckIn', async function(req, res) {
    const {recordId,experimentId,stepName}=req.body;
    const result=await CheckRecordService.cancelCheckIn(recordId,experimentId,stepName);
    res.json(result);
});

router.post('/cabinets', async function(req, res) {
    const result=await CabinetService.getCabinets();
    res.json(result);
});

router.post('/cabinet_grids', async function(req, res) {
    const {cabinetId}=req.body;
    const result=await CabinetService.getCabinetGrids(cabinetId);
    res.json(result);
});

//打开格子
router.post('/openGrid', async function(req, res) {
    const {grid,username}=req.body;
    const result=await CabinetService.openCabinetGrid(grid);
    const cabinet=await CabinetService.getCabinetById(grid.cabinetId);
    const cabinetId=cabinet.HID;
    await CabinetService.saveCabinetLog(cabinetId,grid.number,username,"open");
    res.json(result);
});

router.post('/getGoods', async function(req, res) {
    const {username,grid}=req.body;
    //先修改格子中物品数量
    await KindService.changeGridStore(grid.objectId,grid.count);
    const cabinet=await CabinetService.getCabinetById(grid.cabinetId);
    const cabinetId=cabinet.HID;
    //保存取走记录
    const result=await CabinetService.saveTakenRecord(cabinetId,grid.number,grid.cid,grid.count,grid.kindId,username,false);
    //如果user是教师，从柜子取走物品之后，要将库存数量加回去
    const _user=await UserService.getUserInfo(username);
    const user=ParseHelper.toJSON(_user);
    if(user.isTeacher||user.isAdmin){
        await KindService.change_kind_used_count(grid.kindId,grid.count,"reduce");
    }
    res.json(result);
});






module.exports = router;